package cn.xfdzx.android.apps.shop.activity;


import android.content.Intent;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.adapter.ItemOrderXfdGoodsAdapter;
import cn.xfdzx.android.apps.shop.adapter.RefundReasonAdapter;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.base.BaseMvpActivity;
import cn.xfdzx.android.apps.shop.bean.AfterSalesListMarketBean;
import cn.xfdzx.android.apps.shop.bean.AfterSalesListRetailBean;
import cn.xfdzx.android.apps.shop.bean.ConfirmBeen;
import cn.xfdzx.android.apps.shop.bean.NewOrderBeen;
import cn.xfdzx.android.apps.shop.bean.OrderListBeen;
import cn.xfdzx.android.apps.shop.bean.ReturnReasonBean;
import cn.xfdzx.android.apps.shop.contract.ItemClickListener;
import cn.xfdzx.android.apps.shop.contract.OrderListContract;
import cn.xfdzx.android.apps.shop.evenbus.UpdateMyOrderMessage;
import cn.xfdzx.android.apps.shop.presenter.OrderListPresenter;
import cn.xfdzx.android.apps.shop.util.EmptyUtil;
import cn.xfdzx.android.apps.shop.util.ShopCarPopupWindow;
import cn.xfdzx.android.apps.shop.util.StatusBarUtil;
import cn.xfdzx.android.apps.shop.util.Utils;

public class XFDOrderDetailActivity extends BaseMvpActivity<OrderListPresenter> implements OrderListContract.View {


    @BindView(R.id.iv_location_back)
    ImageView iv_location_back;
    @BindView(R.id.ll_state)
    LinearLayout llState;
    @BindView(R.id.tv_content_title)
    TextView tvContentTitle;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.tv_note)
    TextView tvNote;
    @BindView(R.id.tv_order_num)
    TextView tvOrderNum;
    @BindView(R.id.tv_order_time)
    TextView tvOrderTime;
    @BindView(R.id.tv_good_total_price)
    TextView tvGoodTotalPrice;
    @BindView(R.id.tv_the_freight_price)
    TextView tvTheFreightPrice;
    @BindView(R.id.tv_pay_price)
    TextView tvPayPrice;
    @BindView(R.id.rl_bottom)
    LinearLayout rlBottom;//底部按钮
    @BindView(R.id.tv_look_wuliu_fahuo)
    TextView tvLookWuliuFahuo;//查看物流
    @BindView(R.id.tv_confirm_the_goods)
    TextView tvConfirmTheGoods;//查看订单
    @BindView(R.id.tv_to_pay)
    TextView tvToPay;//去支付
    @BindView(R.id.tv_cancleorder)
    TextView tv_cancleorder;//取消订单
    @BindView(R.id.tv_refund)
    TextView tv_refund;//申请退款
    @BindView(R.id.tv_distribution_type_right)
    TextView tvDistributionTypeRight;//

    @BindView(R.id.tv_time_length)
    TextView tvTimeLength;//剩余多少分钟
    @BindView(R.id.rv_goods)
    RecyclerView rvOrderGoods;
    @BindView(R.id.ll_note)
    LinearLayout ll_note;
    private RelativeLayout.LayoutParams item_bar;
    private OrderListBeen.DataBean dataBean;
    private ItemOrderXfdGoodsAdapter itemOrderXfdGoodsAdapter;
    private List<String> reasonDate;
    private RecyclerView recycleReason;
    private RefundReasonAdapter refundReasonAdapter;
    private TextView tv_why_submit;//提交
    private String selReason;
    private String applyType;//申请类型1取消2售后
    private String orderId;//
    private TextView tv_reasontitle;
    private String pageposition;
    private ShopCarPopupWindow cancel_order_PW;
    @Override
    public int getLayoutId() {
        return R.layout.activity_xfdorder_detail;
    }

    @Override
    public void initView() {
        initHigh();
        StatusBarUtil.setLightStatusBar(this, true, true);
        mPresenter = new OrderListPresenter();
        mPresenter.attachView(this);
        dataBean = (OrderListBeen.DataBean) getIntent().getSerializableExtra("data");
        orderId = dataBean.getOrder_id();
        pageposition = getIntent().getStringExtra("pageposition");
        countdownTime= dataBean.getMiao();
        if (dataBean.getDelivery_method()==0){
            tvDistributionTypeRight.setText("顺丰配送");
        }else  if (dataBean.getDelivery_method()==1){
            tvDistributionTypeRight.setText("大马鹿配送");
        }
        if (dataBean.getDelivery_method()==2){
            tvDistributionTypeRight.setText("自提");
        }
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvOrderGoods.setLayoutManager(linearLayoutManager);
        rvOrderGoods.setItemAnimator(new DefaultItemAnimator());
        rvOrderGoods.setNestedScrollingEnabled(false);
        itemOrderXfdGoodsAdapter = new ItemOrderXfdGoodsAdapter(this);
        itemOrderXfdGoodsAdapter.setOnItemClickListener(new ItemClickListener() {
            @Override
            public void onItemClick(int position) {

            }
        });
        rvOrderGoods.setAdapter(itemOrderXfdGoodsAdapter);
        itemOrderXfdGoodsAdapter.setList(dataBean.getCartInfo());

        tvName.setText(dataBean.getReal_name());
        tvPhone.setText(dataBean.getUser_phone() + "");
        tvAddress.setText(dataBean.getUser_address().trim() + "");
        if (dataBean.getCartInfo().get(0).getStore() != null) {
            tvShopName.setText(dataBean.getCartInfo().get(0).getStore().getName());
        }
        if (EmptyUtil.isNotEmpty(dataBean.getMark())){
            ll_note.setVisibility(View.VISIBLE);
            tvNote.setText(dataBean.getMark());
        }else {
            ll_note.setVisibility(View.GONE);
        }
        tvOrderNum.setText(dataBean.getOrder_id() + "");//订单号
        tvOrderTime.setText(dataBean.get_pay_time() + "");
        tvGoodTotalPrice.setText("¥" + dataBean.getTotal_price());
        tvTheFreightPrice.setText("¥" + dataBean.getTotal_postage());
        tvPayPrice.setText("实付款： ¥" + dataBean.getPay_price());
        if (dataBean.getPaid() == 0) {
            if (dataBean.getMiao() > 0) {
                visibility(1);
                runnable.run();
            } else {
                visibility(2);
            }
        } else {
            //0 待发货 1 已发货 2 已收货待评价 3 已评价 4已完成 5已关闭'  6已申请售后  7 取消订单
            if (dataBean.getStatus() == 0) {
                visibility(3);
            } else if (dataBean.getStatus() == 1) {
                visibility(4);
            } else if (dataBean.getStatus() == 2) {
                visibility(5);
            }else if (dataBean.getStatus() == 3) {
                visibility(13);
            }else if (dataBean.getStatus() == 4) {
                visibility(14);
            }else if (dataBean.getStatus() == 5) {
                visibility(15);
            }else if (dataBean.getStatus() == 6) {
                visibility(16);
            }else if (dataBean.getStatus() == 7) {
                visibility(17);
            }
        }
    }

    private void visibility(int i) {
        tvTimeLength.setVisibility(View.GONE);
        tvLookWuliuFahuo.setVisibility(View.GONE);
        tvConfirmTheGoods.setVisibility(View.GONE);
        tvToPay.setVisibility(View.GONE);
        rlBottom.setVisibility(View.VISIBLE);
        //0 待发货 1 已发货 2 已收货待评价 3 已评价 4已完成 5已关闭'  6已申请售后  7 取消订单
        if (i == 1) {
            tvContentTitle.setText("待支付");
            tvTimeLength.setVisibility(View.VISIBLE);
            tvToPay.setVisibility(View.VISIBLE);
        } else if (i == 2) {
            tvContentTitle.setText("已取消");
            rlBottom.setVisibility(View.GONE);

        } else if (i == 3) {
            tvContentTitle.setText("待发货");
            tvLookWuliuFahuo.setVisibility(View.GONE);
            tvConfirmTheGoods.setVisibility(View.GONE);
            tv_refund.setVisibility(View.GONE);
            tv_cancleorder.setVisibility(View.VISIBLE);
        } else if (i == 4) {
            tvContentTitle.setText("已发货");
            tvLookWuliuFahuo.setVisibility(View.GONE);
            tvConfirmTheGoods.setVisibility(View.GONE);
            tv_refund.setVisibility(View.GONE);
            tv_cancleorder.setVisibility(View.VISIBLE);
        } else if (i == 5) {
            tvContentTitle.setText("已收货");
            tvLookWuliuFahuo.setVisibility(View.GONE);
            tvConfirmTheGoods.setVisibility(View.GONE);
            tv_refund.setVisibility(View.VISIBLE);
            tv_cancleorder.setVisibility(View.GONE);
        } else if (i == 13) {
            tvContentTitle.setText("交易成功");
            tvLookWuliuFahuo.setVisibility(View.GONE);
            tvConfirmTheGoods.setVisibility(View.GONE);
            tv_refund.setVisibility(View.VISIBLE);
            tv_cancleorder.setVisibility(View.GONE);
        }else if (i == 14) {
            tvContentTitle.setText("交易成功");
            tvLookWuliuFahuo.setVisibility(View.GONE);
            tvConfirmTheGoods.setVisibility(View.GONE);
            tv_refund.setVisibility(View.VISIBLE);
            tv_cancleorder.setVisibility(View.GONE);
        }else if (i == 15) {
            tvContentTitle.setText("交易关闭");
            rlBottom.setVisibility(View.GONE);
        }else if (i == 16) {
            tvContentTitle.setText("已售后");
            if (dataBean.getRefund_status() == 1){
                if (EmptyUtil.isNotEmpty(dataBean.getRefund_type())){
                    tvContentTitle.setText("订单处理中"+"(售后原因:"+dataBean.getRefund_type()+")");
                }
            }else if (dataBean.getRefund_status() == 2){
                tvContentTitle.setText("退款成功");
            }else if (dataBean.getRefund_status() == 3){
                if (EmptyUtil.isNotEmpty(dataBean.getRefund_type())){
                    tvContentTitle.setText("退款申请被驳回"+"(售后原因:"+dataBean.getRefund_type()+")");
                }
            }else if (dataBean.getRefund_status() == 4){
                tvContentTitle.setText("退款取消");
            }
            rlBottom.setVisibility(View.GONE);
        }else if (i == 17) {
            tvContentTitle.setText("订单取消中");
            rlBottom.setVisibility(View.GONE);
            if (dataBean.getRefund_status() == 5){
                tvContentTitle.setText("处理中"+"(取消原因:"+dataBean.getCancel_res()+")");
            }else if (dataBean.getRefund_status() == 6){
                tvContentTitle.setText("已处理"+"(取消原因:"+dataBean.getCancel_res()+")");
            }else if (dataBean.getRefund_status() == 7){
                tvContentTitle.setText("已驳回"+"(取消原因:"+dataBean.getCancel_res()+")");
            }
        }

    }

    int countdownTime = 15 * 60;
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (dataBean.getPaid() == 0) {
                countdownTime -= 1;//倒计时总时间减1
                int cha = countdownTime;
                dataBean.setMiao(cha);
                if (cha > 0) {
                    int shi = dataBean.getMiao() / 60;
                    int mill = dataBean.getMiao() - shi * 60;
                    if (mill < 10) {
                        tvTimeLength.setText("剩余时间：" + shi + ":0" + mill);
                    } else {
                        tvTimeLength.setText("剩余时间：" + shi + ":" + mill);
                    }
                    handler.postDelayed(this, 1000);
                } else {
                    visibility(2);
                }
            }

        }
    };

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void onError(Throwable throwable) {

    }

    @Override
    public void onOrderListSuccess(OrderListBeen bean) {

    }

    /**取消订单原因*/
    @Override
    public void getRefundRreasonSuccess(ReturnReasonBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            reasonDate = bean.getData();
            applyType = "1";
            if (null==cancel_order_PW){
                cancel_order_PW = new ShopCarPopupWindow(this, R.layout.pw_cancel_order_stock);
                cancel_order_PW.getRootView().findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        cancel_order_PW.shareClose();
                    }
                });

                cancel_order_PW.getRootView().findViewById(R.id.tv_why_submit).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (EmptyUtil.isNotEmpty(selReason)){
                            Map<String,Object> map = new HashMap<>();
                            map.put("orderId",orderId);
                            map.put("type","2");
                            map.put("reason",selReason);
                            map.put("applyType",applyType);
                            mPresenter.getAfterServiceRequest(map);
                        }else {
                            Toast.makeText(XFDOrderDetailActivity.this, "请选择原因", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        cancel_order_PW.shareClose();
                    }
                });
                tv_why_submit = cancel_order_PW.getRootView().findViewById(R.id.tv_why_submit);
                recycleReason = cancel_order_PW.getRootView().findViewById(R.id.lv_cancel_order_why);
                tv_reasontitle = cancel_order_PW.getRootView().findViewById(R.id.tv_reasontitle);
                tv_reasontitle.setText("取消订单原因");
                recycleReason.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
                refundReasonAdapter = new RefundReasonAdapter(reasonDate);
                recycleReason.setAdapter(refundReasonAdapter);
                refundReasonAdapter.setItemListener(new RefundReasonAdapter.OnItemOnClickListener() {
                    @Override
                    public void onItemClick(int position, String date) {
                        selReason = date;
                        refundReasonAdapter.setItemState(position);
                        tv_why_submit.setBackgroundResource(R.drawable.shape_02c557conner5);
                    }
                });
            }else {
                refundReasonAdapter.refreshDatas(reasonDate);
            }
//            if (EmptyUtil.isNotEmpty(selReason)){
//                tv_why_submit.setBackgroundResource(R.drawable.shape_02c557conner5);
//            }else {
//                tv_why_submit.setBackgroundResource(R.drawable.e3e3e3_3);
//            }

            cancel_order_PW.showPopupWindow();
        }else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void getAfterServiceRequestSuccess(ReturnReasonBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            Toast.makeText(this, "申请成功", Toast.LENGTH_SHORT).show();
            EventBus.getDefault().post(new UpdateMyOrderMessage(pageposition));

            finish();
        }else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    /**申请售后原因*/
    @Override
    public void getReturnReasonSuccess(ReturnReasonBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            reasonDate = bean.getData();
            applyType = "2";
            if (null==cancel_order_PW){
                cancel_order_PW = new ShopCarPopupWindow(this, R.layout.pw_cancel_order_stock);
                cancel_order_PW.getRootView().findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        cancel_order_PW.shareClose();
                    }
                });
                cancel_order_PW.getRootView().findViewById(R.id.tv_why_submit).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (EmptyUtil.isNotEmpty(selReason)){
                            Map<String,Object> map = new HashMap<>();
                            map.put("orderId",orderId);
                            map.put("type","2");
                            map.put("reason",selReason);
                            map.put("applyType",applyType);
                            mPresenter.getAfterServiceRequest(map);
                        }else {
                            Toast.makeText(XFDOrderDetailActivity.this, "请选择原因", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        cancel_order_PW.shareClose();
                    }
                });
                tv_why_submit = cancel_order_PW.getRootView().findViewById(R.id.tv_why_submit);
                recycleReason = cancel_order_PW.getRootView().findViewById(R.id.lv_cancel_order_why);
                tv_reasontitle = cancel_order_PW.getRootView().findViewById(R.id.tv_reasontitle);
                tv_reasontitle.setText("申请售后原因");
                recycleReason.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
                refundReasonAdapter = new RefundReasonAdapter(reasonDate);
                recycleReason.setAdapter(refundReasonAdapter);
                refundReasonAdapter.setItemListener(new RefundReasonAdapter.OnItemOnClickListener() {
                    @Override
                    public void onItemClick(int position, String date) {
                        selReason = date;
                        refundReasonAdapter.setItemState(position);
                        tv_why_submit.setBackgroundResource(R.drawable.shape_02c557conner5);
                    }
                });
            }else {
                refundReasonAdapter.refreshDatas(reasonDate);
            }

            cancel_order_PW.showPopupWindow();
        }else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void finishLoadMore() {

    }

    @Override
    public void onPaySuccess(NewOrderBeen bean, int position) {

    }

    @Override
    public void onConfirmSuccess(ConfirmBeen bean, int position) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            rlBottom.setVisibility(View.GONE);
            tvContentTitle.setText("交易成功");
            EventBus.getDefault().post(new UpdateMyOrderMessage("2"));
        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onGetAfterSalesRetailListSuccess(AfterSalesListRetailBean bean) {

    }

    @Override
    public void onGetIsExceedTimeSuccess(AfterSalesListRetailBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            intent = new Intent(this, AfterServiceMaraketGoodsActivity.class);
            intent.putExtra("data", dataBean);
            startActivity(intent);
        }else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onGetAfterSalesMarketListSuccess(AfterSalesListMarketBean bean) {

    }

    @Override
    protected void onDestroy() {
        handler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }


    private void initHigh() {
        item_bar = (RelativeLayout.LayoutParams) llState.getLayoutParams();
        item_bar.height = StatusBarUtil.getStatusBarHeight(this);
        llState.setLayoutParams(item_bar);
    }

    Intent intent;

    @OnClick({R.id.tv_fuzhi, R.id.tv_to_pay, R.id.tv_look_wuliu_fahuo, R.id.tv_confirm_the_goods,
            R.id.iv_location_back,R.id.tv_cancleorder,R.id.tv_refund})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_fuzhi:
                Utils.copy(this, tvOrderNum.getText().toString());
                Toast.makeText(this, "复制成功", Toast.LENGTH_SHORT).show();
                break;
            case R.id.tv_to_pay:
                intent = new Intent(this, PaymentDeskOrderActivity.class);
                intent.putExtra("orderKey", dataBean.getOrder_id() + "");
                intent.putExtra("totalMoney", dataBean.getPay_price() + "");
                intent.putExtra("from", "routine");
                startActivity(intent);
                break;
            case R.id.tv_look_wuliu_fahuo:
                intent = new Intent(this, XFDOrderWuliuActivity.class);
                intent.putExtra("orderId", dataBean.getOrder_id() + "");
                intent.putExtra("logistics_type", dataBean.getLogistics_type() + "");

                startActivity(intent);

                break;
            case R.id.tv_confirm_the_goods:
                mPresenter.confirm(dataBean.getOrder_id(), 0);
                break;
            case R.id.iv_location_back:
                finish();
                break;
            case R.id.tv_cancleorder://取消订单
                if (Utils.isFastClick()){
                    mPresenter.getRefundRreason();
                }
                break;
            case R.id.tv_refund://申请退款
                if (Utils.isFastClick()){
                    //mPresenter.getReturnReason();
                    mPresenter.getIsExceedTime(orderId);
                }
                break;

        }
    }
}
